<html>
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<meta name="viewport" content="width=device-width, initial-scale=1" />
    <meta charset="utf-8" />
    <!--script src="https://unpkg.com/pdf-lib"></script-->
    
    <script src="pdf-lib.min.js"></script>
    <style type="text/css">
			.center-text {
				text-align: center;
			}
			
			.inputfile {
				opacity: 0;
			}

			.lab {
				border-radius: 10px;
				background-color: #cc99ff;
				font-family: 楷体;
				font-size: 24px;
			}
		</style>
  </head>

  <body>
    <h3 class="center-text">合并Pdf</h3><br />
	<div class="center-text">
		<input type="file" name="file1" id="file1" class="inputfile" accept="application/pdf"  multiple="multiple" /><br />
		<label for="file1" class='lab'>打开Pdf文件</label><br /><br />
		<div class="center-text" id="info"></div>
	</div>	
  </body>

  <script>
		//file extends blob
		const createURL=(file)=>{
			var url = null;
			if (window.createObjectURL != undefined) {
				url = window.createObjectURL(file);
			} else if (window.URL != undefined) { // mozilla(firefox)  
				url = window.URL.createObjectURL(file);
			} else if (window.webkitURL != undefined) { // webkit or chrome  
				url = window.webkitURL.createObjectURL(file);
			}
			return url;
		};
		const downLoad=(url,filename)=>{
			var oA = document.createElement("a");
			oA.download = filename;// 设置下载的文件名，默认是'下载'
			oA.href = url;
			document.body.appendChild(oA);
			oA.click();
			oA.remove(); // 下载之后把创建的元素删除
		}
		const mergePdf=async (files)=>{
			const pdfDoc = await PDFLib.PDFDocument.create();
			for(const file of files){
				//console.log(file);
				const srcDoc = await PDFLib.PDFDocument.load(await fetch(createURL(file)).then(res => res.arrayBuffer()));
				const indices = srcDoc.getPageIndices();
				const copiedPages = await pdfDoc.copyPages(srcDoc, indices);
				//const pages = pdfDoc.getPages();
				for(const page of copiedPages){
					pdfDoc.addPage(page);
				}
			}
			const pdfDataUri = await pdfDoc.saveAsBase64({ dataUri: true });
			downLoad(pdfDataUri,"download.pdf");
		}
		document.getElementById("file1").addEventListener('change', function(event){
			if(this.files.length<1)return;
			mergePdf(this.files);
		});
  </script>
</html>